package com.example.demo1.core.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.example.demo1.core.constants.DataSourcesName;
import com.example.demo1.core.datasource.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

	@Bean("mysqlDataSource")
	@ConfigurationProperties("spring.datasource.mysql")
	public DataSource mysqlDataSource() {
		return DruidDataSourceBuilder.create().build();
	}

	@Bean("taosDataSource")
	@ConfigurationProperties("spring.datasource.taos")
	public DataSource taosDataSource() {
		return DruidDataSourceBuilder.create().build();
	}

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource mysqlDataSource, DataSource taosDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourcesName.MYSQL, mysqlDataSource);
        targetDataSources.put(DataSourcesName.TAOS, taosDataSource);
        
        return new DynamicDataSource(mysqlDataSource, targetDataSources);
    }

}